"use strict";
$(function () {
    yams.menu.select('apartmentManagement');

    yams.page = {
        /**
         * 初始化页面
         */
        init: function () {
            Dolphin.form.parse();
            this.initDataList();
            this.categoryTree();
            this.itemLine();
            this.productList();
            this.bedList();
            this.dayPriceList();
            this.initEvent();
            this.initSearch();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;

            $(".newData").click(function () {
                Dolphin.form.empty('.edit-form');
                let checkedData = me._categoryTree.getChecked();
                if (checkedData.length != 1 || checkedData[0].directory != true) {
                    Dolphin.alert('请选择一个目录节点。');
                    return;
                }
                Dolphin.form.setValue({
                    parent: {
                        id: checkedData[0].id
                    }
                }, '.edit-form');
                $('#dataModal').modal('show');
            });

            $(".newDir").click(function () {
                Dolphin.form.empty('.dir-form');
                let checkedData = me._categoryTree.getChecked();
                if (checkedData.length == 1 && checkedData[0].directory != true) {
                    Dolphin.alert('不可以在公寓节点下挂载目录节点。');
                    return;
                }
                Dolphin.form.setValue({
                    parent: {
                        id: (checkedData[0] && checkedData[0].id) || ''
                    }
                }, '.dir-form');
                $('#dirDataModal').modal('show');
            });

            $("#houseAdd").click(function () {
                Dolphin.form.empty('.house-form');
                let checkedData = me._categoryTree.getChecked();
                if (checkedData.length != 1 || checkedData[0].directory == true) {
                    Dolphin.alert('请选择一个公寓');
                    return;
                }
                Dolphin.form.setValue({
                    apartment: {
                        id: checkedData[0].id
                    }
                }, '.house-form');
                me.clearImage();
                $('#hDataModal').modal('show');
            });

            $(".editData").click(function () {
                let checkedData = me._categoryTree.getChecked();
                if (checkedData.length != 1 || checkedData[0].directory == true) {
                    Dolphin.alert('请选择一个公寓');
                    return;
                }
                if(checkedData[0]._parent){
                    checkedData[0].parent={};
                    checkedData[0].parent.id=checkedData[0]._parent.id;
                }
                Dolphin.form.setValue(checkedData[0], '.edit-form');
                let data=Dolphin.form.getValue('.edit-form');
                $('#dataModal').modal('show');
            });

            $(".modelSave").click(function () {
                let ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    data.directory = false;
                    if (!data.parent.id)
                        delete data.parent;
                    if (data.buildDate)
                        data.buildDate = data.buildDate + " 00:00:00";
                    if (data.startDate)
                        data.startDate = data.startDate + " 00:00:00";
                    Dolphin.ajax({
                        url: '/api/99bcc6d2efca4b50bce3dabb85f990e4',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._categoryTree.reload();
                            $('#dataModal').modal('hide');
                        }
                    });

                }
            });

            $(".dirModelSave").click(function () {
                let ef = $(".dir-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    data.directory = true;
                    if (!data.parent.id)
                        delete data.parent;
                    Dolphin.ajax({
                        url: '/api/99bcc6d2efca4b50bce3dabb85f990e4',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._categoryTree.reload();
                            $('#dirDataModal').modal('hide');
                        }
                    });

                }
            });

            //保存房屋信息
            $(".hModelSave").click(function () {
                //9651431c68a04d54a22f1e2e7faf827b
                let ef = $(".house-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    data['uedit'] = yams.page.um.getContent();
                    data.recommend = !!data.recommend;
                    data.dayRentAble = !!data.dayRentAble;
                    data.monthRentAble = !!data.monthRentAble;
                    data.addBedAble = !!data.addBedAble;
                    console.log(data);
                    Dolphin.ajax({
                        url: '/api/9651431c68a04d54a22f1e2e7faf827b',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            reData.value.beds = data.beds;
                            reData.value.dayPrices = data.dayPrices;
                            Dolphin.ajax({
                                url: '/api/f5e203b61b62430594dd077fc4065bdb',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string(reData.value),
                                onSuccess: function (resData) {
                                    me._itemList.reload();
                                    $('#hDataModal').modal('hide');
                                }
                            });
                        }
                    });
                }
            });

            //克隆功能
            $('#houseCopy').click(function () {
                let ites = me._itemList.getChecked();
                if(ites.length==0){
                    Dolphin.alert('请选择一条记录！');
                    return;
                }else{
                    Dolphin.ajax({
                        url: '/api/319bc41c5fe44dfc9f396b5ace5faf4a@id=' + ites[0].id,
                        type: Dolphin.requestMethod.GET,
                        onSuccess: function (reData) {
                            me.clearImage();
                            let myData = reData.value;
                            myData.apartment = {
                                id: myData.apartmentId
                            };
                            Dolphin.form.setValue(myData, '.house-form');
                            document.getElementById('houseRecommend').checked = myData.recommend;
                            document.getElementById('houseDayRentAble').checked = myData.dayRentAble;
                            document.getElementById('houseMonthRentAble').checked = myData.monthRentAble;
                            document.getElementById('houseAddBedAble').checked = myData.addBedAble;
                            if (reData.value.aimage)
                                $("#aImage").attr('src', '/uploadFiles' + reData.value.aimage);
                            if (reData.value.bimage)
                                $("#bImage").attr('src', '/uploadFiles' + reData.value.bimage);
                            if (reData.value.cimage)
                                $("#cImage").attr('src', '/uploadFiles' + reData.value.cimage);
                            if (reData.value.dimage)
                                $("#dImage").attr('src', '/uploadFiles' + reData.value.dimage);
                            if (reData.value.eimage)
                                $("#eImage").attr('src', '/uploadFiles' + reData.value.eimage);
                            if (reData.value.fimage)
                                $("#fImage").attr('src', '/uploadFiles' + reData.value.fimage);
                            if (reData.value.fimage)
                                $("#gImage").attr('src', '/uploadFiles' + reData.value.gimage);
                            if (reData.value.fimage)
                                $("#hImage").attr('src', '/uploadFiles' + reData.value.himage);
                            if (reData.value.fimage)
                                $("#iImage").attr('src', '/uploadFiles' + reData.value.iimage);
                            if (reData.value.fimage)
                                $("#jImage").attr('src', '/uploadFiles' + reData.value.jimage);
                            if (reData.value.fimage)
                                $("#kImage").attr('src', '/uploadFiles' + reData.value.kimage);
                            if (reData.value.fimage)
                                $("#lImage").attr('src', '/uploadFiles' + reData.value.limage);

                            me._bedList.loadData({rows: reData.value.properties.beds});
                            me._dayPriceList.loadData({rows: reData.value.properties.dayPrices});

                            $("#houseId").val("");
                            $("#houseCode").val("");

                            $('#hDataModal').modal('show');
                        }
                    });
                }
            });

            $(".addProduct").click(function () {
                $('#addPrdDataModal').modal('show');
            });

            $(".saveProduct").click(function () {
                console.log(me._productList.data.rows);
                let data = {id: me._productList.houseId, products: me._productList.data.rows};
                Dolphin.ajax({
                    url: '/api/4661c4fae7c5416a83d1709ecada4c2d',
                    type: Dolphin.requestMethod.PUT,
                    data: Dolphin.json2string(data),
                    onSuccess: function (reData) {
                        $('#prdDataModal').modal('hide');
                    }
                });
            });

            $(".fileinput-del-btn").click(function () {
                $('#' + $(this).data('ind') + 'ImageInput').val('');
                $("#" + $(this).data('ind') + 'Image').attr('src', '/page/images/house_default.png');
            });

            $(".btn-query").click(function () {
                me._itemList.load(null, Dolphin.form.getValue('.query-form'))
            });
        },

        initDataList: function () {
            let me = this;
        },

        categoryTree: function () {
            let me = this;
            this._categoryTree = new Dolphin.TREE({
                defaultId: -1,
                requestKey: 'parentId',
                panel: '#categoryTree',
                url: '/api/bf6230f25b974827bc3dec9dd789edc4@parentId={parentId}',
                multiple: false,
                onChecked: function (data) {
                    me.selectNode = data;
                    if (data.directory) {
                        $("#basicInfoPanel").hide();
                        me._itemList.load(null,{
                            _cityId: data.code !== 'rootRoom'?data.id:''
                        });
                    } else {
                        $("#basicInfoPanel").show();
                        Dolphin.form.empty('#basicInfoPanel');
                        Dolphin.form.setValue(data, '#basicInfoPanel');
                        me._itemList.load(null,{
                            apartment_id_obj_ae: data.id
                        });
                    }
                },
                onLoad: function () {
                    if (this.data && this.data.length > 0) {
                        let n = this.data[0];
                        this.expend(n);
                    }
                },
                nameField: function (data) {
                    if (!data.directory) {
                        return "<span style='color: #00ff;'>" + data.name + "</span>";
                    }
                    return data.name;
                }
            });
        },

        clearImage: function () {
            $(".image-name").val('');
            $(".imageShowBody").attr('src', '/page/images/house_default.png');
        },

        itemLine: function () {
            let me = this;
            this._itemList = new Dolphin.LIST({
                panel: '#itemList',
                url: '/api/9651431c68a04d54a22f1e2e7faf827b',
                ajaxType: 'post',
                mockPathData: ['id'],
                queryParams: {
                    account : yams.context.checkAdmin()
                },
                data: {rows: [], total: 0},
                pagination: true,
                multiple: false,
                columns: [{
                    code: 'name',
                    title: '名称'
                }, {
                    code: 'houseNumber',
                    title: '房号'
                }, {
                    code: 'houseType',
                    title: '户型',
                    formatter: function (val) {
                        return Dolphin.enum.getEnumText("houseType", val);
                    }
                }, {
                    code: 'floor',
                    title: '楼层'
                }, {
                    code: 'area',
                    title: '面积'
                }, {
                    code: 'monthly',
                    title: '月租'
                }, {
                    code: 'propertyFee',
                    title: '物业费'
                },{
                    code: 'recommend',
                    title: '推荐',
                    formatter: function (val) {
                        return val ? "是" : "否";
                    }
                }, {
                    code: 'statusName',
                    title: '状态'
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '190px',
                    formatter: function (val, row, index) {
                        let html = [];
                        if (row.apartmentId == me.selectNode.id) {
                            html.push(yams.buttons.edit({
                                id: row.id
                            }));
                        }
                        html.push('<a class="btn btn-outline btn-circle btn-sm dark prdBtn" data-id="' + val + '"  href="javascript:void(0);"><i class="fa fa-book"></i>资产信息</a>');
                        return html.join('');
                    }
                }],
                onLoadSuccess: function (data) {
                    yams.buttons.editCallback('319bc41c5fe44dfc9f396b5ace5faf4a', 'id', function (reData) {
                        me.clearImage();
                        let myData = reData.value;
                        myData.apartment = {
                            id: myData.apartmentId
                        };
                        Dolphin.form.setValue(myData, '.house-form');
                        document.getElementById('houseRecommend').checked = myData.recommend;
                        document.getElementById('houseDayRentAble').checked = myData.dayRentAble;
                        document.getElementById('houseMonthRentAble').checked = myData.monthRentAble;
                        document.getElementById('houseAddBedAble').checked = myData.addBedAble;

                        yams.page.um.setContent(reData.value['uedit']);
                        if (reData.value.aimage) {
                            $("#aImage").attr('src', '/uploadFiles' + reData.value.aimage);
                        }
                        if (reData.value.bimage) {
                            $("#bImage").attr('src', '/uploadFiles' + reData.value.bimage);
                        }
                        if (reData.value.cimage)
                            $("#cImage").attr('src', '/uploadFiles' + reData.value.cimage);
                        if (reData.value.dimage)
                            $("#dImage").attr('src', '/uploadFiles' + reData.value.dimage);
                        if (reData.value.eimage)
                            $("#eImage").attr('src', '/uploadFiles' + reData.value.eimage);
                        if (reData.value.fimage)
                            $("#fImage").attr('src', '/uploadFiles' + reData.value.fimage);
                        if (reData.value.gimage)
                            $("#gImage").attr('src', '/uploadFiles' + reData.value.gimage);
                        if (reData.value.himage)
                            $("#hImage").attr('src', '/uploadFiles' + reData.value.himage);
                        if (reData.value.iimage)
                            $("#iImage").attr('src', '/uploadFiles' + reData.value.iimage);
                        if (reData.value.jimage)
                            $("#jImage").attr('src', '/uploadFiles' + reData.value.jimage);
                        if (reData.value.kimage)
                            $("#kImage").attr('src', '/uploadFiles' + reData.value.kimage);
                        if (reData.value.limage)
                            $("#lImage").attr('src', '/uploadFiles' + reData.value.limage);

                        me._bedList.loadData({rows: reData.value.properties.beds});
                        me._dayPriceList.loadData({rows: reData.value.properties.dayPrices});

                        $('#hDataModal').modal('show');
                    });

                    $('.prdBtn').click(function () {
                        me._productList.houseId = $(this).data('id');
                        me._productList.query({house_id_obj_ae: $(this).data('id')});
                        $('#prdDataModal').modal('show');
                    });
                },
                onCheck: function (data, row, thisInput) {
                },
                onChecked: function (data, row, thisCheckbox) {
                    me.curSelect = data;
                },
                onUnchecked: function (data) {
                }
            });
        },

        productList: function () {
            let me = this;
            this._productList = new Dolphin.LIST({
                houseId: '',
                panel: '#productList',
                url: '/api/ffd4a6ca2c74462ba709ce09d61071db',
                ajaxType: 'post',
                mockPathData: ['id'],
                data: {rows: [{}], total: 0},
                pagination: false,
                multiple: false,
                editFlag: true,
                editListName: 'products',
                columns: [{
                    code: 'id',
                    hidden: true,
                    title: '数据主键'
                }, {
                    code: 'code',
                    title: '资产编码',
                    width: '180px'
                }, {
                    code: 'name',
                    title: '资产名称'
                }],
                onLoadSuccess: function () {
                }
            });
        },

        bedList: function () {
            let me = this;
            this._bedList = new Dolphin.LIST({
                panel: '#bedList',
                ajaxType: 'post',
                mockPathData: ['id'],
                data: {rows: [{}], total: 0},
                pagination: false,
                multiple: false,
                editFlag: true,
                editListName: 'beds',
                rowIndex: false,
                checkbox: false,
                columns: [{
                    code: 'id',
                    hidden: true,
                    title: '数据主键'
                }, {
                    code: 'bedType',
                    title: '床铺类型',
                    width: '180px',
                    editType: 'select',
                    options: 'bedType'

                }, {
                    code: 'bedLength',
                    title: '长'
                }, {
                    code: 'bedWidth',
                    title: '宽'
                }],
                onLoadSuccess: function () {
                }
            });
        },

        dayPriceList: function () {
            let me = this;
            this._dayPriceList = new Dolphin.LIST({
                panel: '#dayPriceList',
                ajaxType: 'post',
                mockPathData: ['id'],
                data: {rows: [{}], total: 0},
                pagination: false,
                multiple: false,
                editFlag: true,
                editListName: 'dayPrices',
                rowIndex: false,
                checkbox: false,
                columns: [{
                    code: 'id',
                    hidden: true,
                    title: '数据主键'
                }, {
                    code: 'shortRentType',
                    title: '短租类型',
                    editType: 'select',
                    options: 'shortRentType'

                }, {
                    code: 'dayPrice',
                    title: '价格'
                }],
                onLoadSuccess: function () {
                }
            });
        },

        initSearch: function () {
            let me = this;
            $("#skuId").bsSuggest({
                delayUntilKeyup: true,
                allowNoKeyword: false,   //是否允许无关键字时请求数据。为 false 则无输入时不执行过滤请求
                multiWord: false,         //以分隔符号分割的多关键字支持
                separator: ",",          //多关键字支持时的分隔符，默认为空格
                getDataMethod: "url",    //获取数据的方式，总是从 URL 获取
                effectiveFields: ["code", "name", "typeName"],
                effectiveFieldsAlias: {code: "编码", name: "名称", typeName: "类型"},
                idField: 'id',
                keyField: 'code',
                url: (yams.context.contextPath == '/' ? '' : yams.context.contextPath) + '/api/293ff19f7b04482e9adb902893c8a685', //优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数
                listStyle: {
                    'padding-top': 0,
                    'max-height': '425px',
                    'max-width': '800px',
                    'overflow': 'auto',
                    'border': '1px solid',
                    'width': 'auto',
                    'transition': '0.3s',
                    '-webkit-transition': '0.3s',
                    '-moz-transition': '0.3s',
                    '-o-transition': '0.3s'
                },                              //列表的样式控制
                listAlign: 'left',              //提示列表对齐位置，left/right/auto
                listHoverStyle: 'background: #07d; color:#000', //提示框列表鼠标悬浮的样式
                fnAdjustAjaxParam: function (keyword, opt) {
                    return {
                        type: 'POST',
                        data: {
                            houseId: '-1',
                            code: keyword
                        },
                        dataType: 'json',
                        beforeSend: function (XMLHttpRequest) {
                            let requestHeaderParam = Dolphin.defaults.ajax.requestHeader;
                            for (let key in requestHeaderParam) {
                                XMLHttpRequest.setRequestHeader(key, requestHeaderParam[key]);
                            }
                        }
                    };
                },
                fnProcessData: function (json) {    // url 获取数据时，对数据的处理，作为 fnGetData 的回调函数
                    let index, len, data = {value: []};
                    data.value = json.rows;
                    //字符串转化为 js 对象
                    return data;
                }
            }).on('onDataRequestSuccess', function (e, result) {
                console.log('--', result);
                if (result.total == 0) {
                    console.log($(this).parent());
                }
            }).on('onSetSelectValue', function (e, keyword, data) {
                me._productList.addRowWithData(data);
                $('#addPrdDataModal').modal('hide');

            }).on('onUnsetSelectValue', function () {
            });
        },

        /**
         * 一些页面DOM对象和事件的销毁
         */
        destroy: function () {
        }
    };
});